/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package helpdesk;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;

/**
 * DBManager
 *
 * Used to allocate database connections for SQL queries.
 *
 * @author brian
 */
public class DBManager {
    private static DataSource dSource;
    private static boolean isInitialized=false;

    /**
     * Automatically invoked by getConnection if the connection has not been
     * initialized. Currently, we are not using this, as Tomcat's connection
     * pooling would not work.
     *
     * @throws SQLException
     */
    private static synchronized void init() throws SQLException
    {
        if (!isInitialized)
        {
            try
            {
                InitialContext ctx = new InitialContext();
                if (ctx == null)
                    throw new SQLException("DBManager: JNDI lookup failed");
                dSource = (DataSource)ctx.lookup("java:/comp/env/jdbc/postgres");
                if (dSource == null)
                    throw new SQLException("DBManager: JNDI lookup failed");
            }
            catch (NamingException ex)
            {
                throw new SQLException("DBManager: JNDI lookup failed");
            }

            isInitialized = true;
        }

    }


    /**
     * Get a database connection.
     * 
     * Do not forget to close the connection; failure to do so can cause
     * deadlock (if we used pooling) or a performance penalty.
     *
     * Normally would call init automatically, but we are using a different
     * connection method. We may decide to use connection pooling later.
     *
     * @return
     * @throws SQLException
     */
    public static synchronized Connection getConnection() throws SQLException
    {
        /*
        if (!isInitialized)
            init();
         */
        //
        try
        {
        Class.forName("org.postgresql.Driver");
        }
        catch (ClassNotFoundException e)
        {
            throw new SQLException("Could not load SQL driver");
        }


        return DriverManager.getConnection("jdbc:postgresql:helpdesk", "helpdesk", "kitten44");

        // return dSource.getConnection();
    }
}
